const api = require('../../api/api.js');
const app = getApp();
Page({
  data: {
    card: true,
    sites: [],
    imgUrl: app.globalData.imgUrl + 'siteImage/',
    inputKey: '默认搜索所有农场！'
  },
  onLoad(o) {
    let that = this;
    let kw = o.kw;
    if (kw !== '') {
      that.setData({
        inputKey: kw
      });
    }
    that.querySitesByKeyword(kw);
  },
  confirmed(e) {
    let kw = e.detail.value.trim();
    this.querySitesByKeyword(kw);
    this.addRecord(kw);
  },
  querySitesByKeyword(kw) {
    let that = this;
    api.querySitesByKeyword({
      data: {
        keys: kw
      },
      success(res) {
        console.log(res.data);
        res.data.sites.map((i) => {
          if (i.image === '') {
            i.image = 'noImage.png'
          }
        });
        that.setData({
          sites: res.data.sites
        });
      }
    });
  },
  addRecord(kw) {
    let that = this;
    wx.getStorage({
      key: 'userId',
      success: function(res) {
        api.addHistoricalSearchRecord({
          data: {
            userId: res.data,
            keyword: kw
          },
          success() {
            let pages = getCurrentPages();
            let prepage = pages[pages.length - 2];
            prepage.onLoad();
          }
        });
      },
    })
  },
  changeLayout() {
    let card = this.data.card;
    this.setData({
      card: !card
    });
  },
  goToSitePage(e){
    wx.navigateTo({
      url: `/pages/site/site?siteId=${e.currentTarget.dataset.siteid}`
    })
  }
})